//var socket = io("ws://127.0.0.1:8000");
var socket = io("ws://114.55.38.80:8000");
socket.on('connect', function(sockets) {
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	socket.emit("login", {
		"username": $("#name").attr("data-name"),
		"sex": 1,
		"marking": 1,
		"userrole": 3,
		"openid": null,
		"token": msg.token
	});
});
//$("input").attr("disabled","disabled")
//接收表单数据
var gengers = null;
socket.on("sendoerder", function(data) {
	console.log(data);
	let roomid = $(".username").attr("data-id");
	if(data) {
		$('.Basic_information').css({
			'height': '315px'
		});
	}
	//senduserinfo(data); //保存用户信息
	$('div[roomid="' + roomid + '"] .biaodaninfo').css("display", "none");
	$('div[roomid="' + roomid + '"] .drawing_input').css("display", "block");
	//修改按钮显示
	$('div[roomid="' + roomid + '"] .modification').css("display", "block");
	//发送基本信息表单按钮隐藏
	$('div[roomid="' + roomid + '"] .Send_the_basic_information_form').css("display", "none");
	$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "0px");

    //用户基本id
    $('div[roomid="' + roomid + '"]').attr("uderinfo_id",data._id);
    
	if(data.genger == "男") {
		gengers = 1;
		$('div[roomid="' + roomid + '"] .gender_all').children().remove();
		let htmls = '<div class="gender_all_men">';
		htmls += '<span class="all_men">男</span>';
		htmls += '</div>';
		$('div[roomid="' + roomid + '"] .gender_all').append(htmls);
		//$("input").attr("disabled", "disabled");
	} else if(data.genger == "女") {
		gengers = 2;
		$('div[roomid="' + roomid + '"] .gender_all').children().remove();
		let htmls = '<div class="gender_all_wormen">';
		htmls += '<span class="wormen">女</span>';
		htmls += '</div>';
		$('div[roomid="' + roomid + '"] .gender_all').append(htmls);
		//$("input").attr("disabled", "disabled");
	}

	$('div[roomid="' + roomid + '"] .username_S_left').text(data.username);
	$('div[roomid="' + roomid + '"] .riqi').text(data.date);
	$('div[roomid="' + roomid + '"] .height_S_left').text(data.height_);
	$('div[roomid="' + roomid + '"] .weight_S_left').text(data.weight_);

	if(data.Medical_ || data.allergies_) {
		$('div[roomid="' + roomid + '"] .input_medical_left').text(data.Medical_);
		$('div[roomid="' + roomid + '"] .input_allergy_left').text(data.allergies_);
	} else {
		$('div[roomid="' + roomid + '"] .input_medical_left').text("无");
		$('div[roomid="' + roomid + '"] .input_allergy_left').text("无");
	}
});

//表单数据信息 
socket.on("sendoerder1", function(data) {
	console.log(data);
	let roomid = $(".username").attr("data-id");
	let formDate = '';
	if(data.subject) {
		var suject_datas = data.subject;
		if(!subject[data._id]) {
			subject[data._id] = [];
			subject[data._id].push(data);
			_privateSingles = data._id;
		} else {
			subject[data._id][0] = data;
			_privateSingles = data._id;
		};
		for(var b = 0; b < suject_datas.length; b++) {
			//console.log(suject_datas[b])
			if(suject_datas[b].type == 1) { //单选
				if(suject_datas[b].select instanceof Array) {
					let str = '';
					for(let a = 0; a < suject_datas[b].select.length; a++) {
						if(suject_datas[b].select[a].checked == true) {
							str += `<div class="color_all_style">
								<input type="radio" name="order${b}" checked disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
						} else {
							str += `<div class="color_all_style">
								<input type="radio" name="order${b}" disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
								<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
						}
					};
					let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(单选)
					<div class="Day_to_day_A">${str}</div>
					</div>`;
					formDate += formDates;
				};
			};
			if(suject_datas[b].type == 2) { //多选
				if(suject_datas[b].select instanceof Array) {
					let str = '';
					for(let a = 0; a < suject_datas[b].select.length; a++) {
						if(suject_datas[b].select[a].checked == true) {
							str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" checked disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
						} else {
							str += `<div class="color_all_style">
														<input type="checkbox" name="order${b}" disabled class="input_all_style" value="${suject_datas[b].select[a].selectResult}">
														<span>${suject_datas[b].select[a].selectResult}</span>
							</div>`
						}

					};
					let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(多选)
					<div class="Day_to_day_A">${str}</div>
					</div>`;
					formDate += formDates;
				};
			};
			if(suject_datas[b].type == 3) { //简答
				let str = `<textarea name="textareas" cols="30" rows="2"  class="textarea${b+1}" style='margin-left: -20px;width: 100%;height: 70px;background: white;border-radius: 5px;'>${suject_datas[b].describe}</textarea>`
				let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}'>${b+1}、${suject_datas[b].subjectName}(简答)
					<div class="Day_to_day_A">${str}</div>
					</div>`;
				formDate += formDates;

			};
			if(suject_datas[b].type == 4) { //图片
				let stars=``;
				for (let a=0;a<suject_datas[b].img.length;a++) {
					stars+=`<div class="show_imgs"><samp class="deleteimg" onclick="deleteimg(this)">x</samp><img src="${suject_datas[b].img[a]}" class="layui-upload-img"></div>`
				}
				let str = `<div class="" style=" display: flex;	flex-direction: row;flex-wrap: wrap; " > 
								<div style="height:110px;" >
								    <div class="layui-upload-list" style="height: 93px;margin:0 5px;display: flex;flex-direction: row  ">
								      ${stars}
								    </div>
								</div>
								<div class="layui-upload">
									 <img src="img/uploadimg.png" class="upload_Orderimg"/>
									  <input type="file" name="files"  class="upload_img" imgsize="${suject_datas[b].size}" onchange="creatImg(this.files,this)" />
								</div>	
						</div>`
				let formDates = `<div class="user_news_all_" data_item="${b}" data_index='${suject_datas[b].type}' style="display: flex;	flex-direction: column;">
				    <p>${b+1}、${suject_datas[b].subjectName}(图片) </p>
					<div class="Day_to_day_A">${str}</div>
					</div>`;
				formDate += formDates;
			};
		};
	};
	$('div[roomid="' + roomid + '"] .men_input_change input[type="radio"]').attr("disabled", "disabled")
	$('div[roomid="' + roomid + '"] .men_input_change input[type="checkbox"]').attr("disabled", "disabled");
	$('div[roomid="' + roomid + '"] .men_input_change .upload_Orderimg').css("display", "none");
	$('div[roomid="' + roomid + '"] .men_input_change textarea').attr("disabled", "disabled");
	$('div[roomid="' + roomid + '"] .single_submit_S_All').css({
		'display': 'block'
	});
	$('div[roomid="' + roomid + '"] .men_input_change_three').html(formDate);
	$('div[roomid="' + roomid + '"] .men_input_change').css('display', 'block');
	$("div[roomid='" + roomid + "'] .substitute_women").children().remove();
	$("div[roomid='" + roomid + "'] .Collect_the_singles").css("margin-top", "0px");
});

//上线用户信息
socket.on("userlogin", function(data) {
	$(".doctor_select").children("option").remove();
	//$(".yaoqing").children("option").remove();
	var userinfo = data.userlist;
	var html = "";
	onlindoctor(data.userlist); //更新医生列表
	console.log(data)
	//存储socket用户
	socketList=data.userlist;
	if(data.userlist.length != 0) {
		for(let a = 0; a < userinfo.length; a++) {
			if(userinfo[a].userrole == 1 || userinfo[a].userrole == 6) {
				html += '<option value="" userrole="' + userinfo[a].userrole + '" data-id="' + userinfo[a].id + '">' + userinfo[a].name + '</option>'; //医生信息
			}
		};
		//$(".doctor_select").html(html);
		//$(".yaoqing").html(html);
	}
});

//房间信息
const roominfos = [];
var arr_all = []
socket.on("roominfo", function(data) {
	console.log(data)
	var username = "";
	//$(".list-group").children("li").remove();
	//$(".jiedai").text("");
	var html = "";
	var arr_s = [];
	var arr_ = []
	var type = ""
	for(let a in data) {
		console.log(data[a])
		arr_s.push(data[a])
		roominfos.push(data[a]);
	}
	return;
	for(var i = 0; i < arr_s.length; i++) {
		//如果当前数组的第i已经保存进了临时数组，那么跳过， 
		//否则把当前项push到临时数组里面 
		if(arr_.indexOf(arr_s[i]) == -1) arr_.push(arr_s[i]);
	}
	console.log(arr_s)
	console.log(arr_)
	for(let i = 0; i < arr_.length; i++) {
		if(arr_[i].marking == 1) {
			type = "pc1";
			username = arr_[i].rooname
		}
		if(arr_[i].marking == 2) {
			type = "wx1";
			username = arr_[i].nickname
		}
		if(arr_[i].marking == 3) {
			type = "app1"
			username = arr_[i].rooname
		}
		html +=
			`
		   <li class="list-group-item"  data-type = "${type}" data-id="${arr_[i].socket_id}"   data-index="${i}"   style="color:${i == 0 ? '#1abb9c' : ''}; border-right:1px solid #EEEFF0;">
		   <div class="flex-item">
		   <img src="img/${type}.png" class="img"/>
		   </div>
		   <div class="flex-item center">
		   <span class="text1">${username}</span><br/>
		   <span class="text2">${arr_[i].rooname}</span>
		   </div>
		   <div class="flex-item rights">
		   <span>${i == 0 ? '现在' : arr_[i].data}</span>
		  
		   </div>
		   </li>
		   `
	}
	$(".list-group").html(html);
	$(".jiedai").text(arr_s.length);
	//	arr.length = 0;
	$('.list-group').on('click', 'li', function(e) {
		let index = e.currentTarget.attributes[3].nodeValue
		if(index !== 0) {
			var remove_ = arr_.splice(index, 1)
			console.log(remove_)
			arr_.unshift(remove_[0])
			console.log(arr_)
			$('.list-group').children('li').remove()
			var htmls = "";
			for(let i = 0; i < arr_.length; i++) {
				console.log(arr_)
				if(arr_[i].marking == 1) {
					type = "pc1";
					username = arr_[i].rooname
				}
				if(arr_[i].marking == 2) {
					type = "wx1";
					username = arr_[i].nickname
				}
				if(arr_[i].marking == 3) {
					type = "app1"
					username = arr_[i].rooname
				}
				htmls +=

					`
							   <li class="list-group-item"          data-type = "${type}" data-id="${arr_[i].socket_id}"   data-index="${i}"   style="color:${i == 0 ? '#1abb9c' : ''}">
							   <div class="flex-item">
							   <img src="img/${type}.png" class="img"/>
							   </div>
							   <div class="flex-item center">
							   <span class="text1">${username}</span><br/>
							   <span class="text2">${arr_[i].rooname}</span>
							   </div>
							   <div class="flex-item rights">
							   <span>${i == 0 ? '现在' : arr_[i].data}</span><br/>
						
							   </div>
							   </li>
							   `
			}
			$('.list-group').append(htmls)
		}
	})
})
const chatroom = {};


//监听房间信息
socket.on("msg", function(id, msg) {
	console.log(msg);
	var time = new Date();
	if(!chatroom[msg.roomID]) {
		chatroom[msg.roomID] = [];
	};
	chatroom[msg.roomID].push(msg);
	let roomid = $(".closes").attr("data-id");
	if(msg.roomID == roomid) {
		if(msg.is != $("#name").attr("data-username")) {
			if(msg.imggs != "") {
				//var html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><img  class="chatimg" src="' + msg.imggs + '"/><div class="left-d"><divclass="a3"></div></div></div></div></li>';
				//var html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><span class="span_times">' + (msg.username) + '&nbsp;' + time.getHours() + ":" +(time.getMinutes().toString().length==1?"0"+time.getMinutes():time.getMinutes())+ ":" + (time.getSeconds().toString().length==1?"0"+time.getSeconds():time.getSeconds()) + '</span> <divclass="a3"><img  class="chatimg" src="' + msg.imggs + '"/></div></div></div></div></li>';
				    let htmls=`<li>
							<div class="layim-chat-user">
							<img src="${msg.anonymityImg}">
							<cite>${msg.username}<i>${moment().format('hh:mm:ss')}</i></cite>
							</div>
							<div class="layim-chat-text" style="color: #18BB9B;">
							<img class="chatimg" src="${msg.imggs}">
							</div>
							</li>`
				 $('.chat-thread').append(htmls);
			} else {
				var massage = "";
				const massages = [{
						a: "已发送妇科表单",
						b: "已发送男科表单",
						c: "已发送基本信息表单"
					},
					{
						a: "已接收妇科表单",
						b: "已接收男科表单",
						c: "已接收基本信息表单"
					}
				]
				if(msg.msg == massages[0].a || msg.msg == massages[0].b || msg.msg == massages[0].c) {
					if(msg.msg == massages[0].a) {
						massage = massages[1].a;
					}
					if(msg.msg == massages[0].b) {
						massage = massages[1].b;
					}
					if(msg.msg == massages[0].c) {
						massage = massages[1].c;
					}
					//let html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><span class="span_times">' + (msg.username) + "   " + time.getHours() + ":" + (time.getMinutes().toString().length==1?"0"+time.getMinutes():time.getMinutes()) + ":" +(time.getSeconds().toString().length==1?"0"+time.getSeconds():time.getSeconds()) + '</span><div  class="a3">' + massage + '</div></div></div></div></li>';
					let htmls=`<li>
							<div class="layim-chat-user">
							<img src="${msg.anonymityImg}">
							<cite>${msg.username}<i>${moment().format('hh:mm:ss')}</i></cite>
							</div>
							<div class="layim-chat-text" style="color: #18BB9B;">
							  <p>${massage}</p>
							</div>
							</li>`
					$('.chat-thread').append(htmls)
				} else {
					massage = msg.msg;
					///let html = '<li class="say_layout"><div class="Tosay"><div class="left-Text"><div class="left-d"><span class="span_times">' + (msg.username) + "   " + time.getHours() + ":" + (time.getMinutes().toString().length==1?"0"+time.getMinutes():time.getMinutes()) + ":" + (time.getSeconds().toString().length==1?"0"+time.getSeconds():time.getSeconds()) + '</span><div  class="a3">' + massage + '</div></div></div></div></li>';
					let htmls=`<li>
							<div class="layim-chat-user">
							<img src="${msg.anonymityImg}">
							<cite>${msg.username}<i>${moment().format('hh:mm:ss')}</i></cite>
							</div>
							<div class="layim-chat-text" style="color: #18BB9B;">
							 <p>${massage}</p>
							</div>
							</li>`
					$('.chat-thread').append(htmls)
				}
			}
		};
	} else {
		let roomlist = $(".list-group").children("li");
		for(let a = 0; a < roomlist.length; a++) {
			if(roomlist[a].attributes.rooname.value == msg.roomID) {
				$(roomlist[a]).children(".rights").children(".layui-bg-green").css("display", "block");
				let roomlists = $(".list-group").children("li");
				for(let a = 0; a < roomlists.length; a++) {
					if(roomlists[a].attributes.rooname.value == msg.roomID) {
						$(".list-group").prepend(roomlists[a]);
					}
				}
			}
		}
	}
	let div = document.getElementsByClassName('chat-thread')[0];
	div.scrollTop = div.scrollHeight;
});
//监听房间离开加入信息
socket.on("sys", function(user, id, evens,userrole) {
	let userinfo = id[id.length - 1].username;
	   if(userrole==1){
	   	 $('.chat-thread').append('<div class="layim-chat-system"><span layim-event="chatLog"><a>医生'+user+'</a></span></div>');
	   } 
	   if(userrole==3){
	   	 $('.chat-thread').append('<div class="layim-chat-system"><span layim-event="chatLog"><a>客服'+user+'</a></span></div>');
	   } 
	   if(userrole==6){
	   	 $('.chat-thread').append('<div class="layim-chat-system"><span layim-event="chatLog"><a>助理'+user+'</a></span></div>');
	   } 
});
//药师审核通过之后通知信息
socket.on('notification_msg', function(pass, passid) {
	console.log(pass);
	console.log(passid);
	$('.chat-thread').append(`<div class="layim-chat-system"><span layim-event="chatLog"><a id="${passid}" onclick="Diagnosis_Order(event)">电子诊断单已审核通过,立即查看</a></span></div>`);
	layer.open({
		type: 1,
		title: ['新消息'],
		area: ['280px', '180px'],
		shade: 0,
		offset: 'rb',
		anim: 2,
		closeBtn: false,
		content: "<div  style='word-wrap: break-word;margin: 0 auto;width: 200px;text-align: center;margin-top:10px;color: black;' electronic_id=" + passid + ">电子诊断单已审核通过,是否立即查看</div>",
		btn: ['立即查看', '关闭'],
		btn1: function(index) {
			//基本信息
			layer.close(index);
			layer.open({
			  type: 2,
			  title: '电子问诊单详情',
			  shadeClose: true,
			  shade: 0.8,
			  area: ['90%', '90%'],
			  content: `../postpaper/postpaper.html?id=${passid}&&name=3` //iframe的url
			});
		},
		btn2: function(index) {
			layer.close(index);
		},
		zIndex: layer.zIndex,
		success: function(layero) {
			layer.setTop(layero); //重点2\
			layero.find(".layui-layer-title").before("<span></span>");
			layero.find(".layui-layer-title").css({
				"font-weight": "500",
				"width": "100%"
			});
			layero.find(".layui-layer-title").addClass("glyphicon glyphicon-cog");
			layero.find(".layui-layer-title").css({
				"font-weight": "500"
			});
			layero.find(".layui-layer-btn").css({
				"border-top": "1px solid rgb(240,240,240)",
				"text-align": "center"
			});
			layero.find(".layui-layer-btn0").css({
				"width": "100px",
				"border-color": "white",
				"background-color": "white",
				"color": "#1abb9c",
				"border-right": "1px solid rgb(240,240,240)"
			});
			layero.find(".layui-layer-btn1").css({
				"width": "100px",
				"border-color": "white",
				"background-color": "white",
				"color": "rgb(145, 141, 141)"
			})
		}
	});
});
//发送私信通知消息
socket.on("private_msg", (data) => {
	console.log(data);
});

function senduserinfo(data) {
	const pares = {
		userid: data.roomID, //用户id 商城登陆用户id 小程序openid
		name: data.username, //姓名
		birthday: data.date, //出生日期
		gender: data.genger, //性别
		height: data.height_, //身高
		Weight: data.weight_, //体重
		medicalHistory: data.Medical_, //病史
		allergy: data.allergies_, //是否过敏
		server: {
			id: $("#name").attr("data-name"),
			name: $("#name").attr("data-name")
		}, //办理人
		information: null, //基本情况收集单
		serMedicinal: [{
			Rx_Drug: ""
		}] //结束诊疗时间
	};
	let a = 1;
	if(a = 1) {
		pares.assistant = {
			id: "cc",
			name: "cc"
		}
	} else {
		pares.doctor = {
			id: "",
			name: ""
		}
	}
};

//医生/助理信息列表https://xcx.juseyx.cn/service/onlindoctor
function onlindoctor(info) {
	let msg = window.sessionStorage['user_msg'];
	msg = JSON.parse(msg);
	$.ajax({
		url: serviceURL+"onlindoctor",
		traditional: true,
		type: "post",
		dataType: "json",
		data: {},
		headers: {
			'Authorization': 'Bearer ' + msg.token
		},
		async: true,
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				//$(".yaoqing").children("option").remove();
				var html = "";
				for(let b = 0; b <res.content.length; b++) {
					for(let a = 0; a < info.length; a++) {
						if(res.content[b].userName==info[a].name) {
							res.content[b].todo_doctor=res.content[b].todo_doctor==0?"空闲":res.content[b].todo_doctor;
							html += '<option value="" userrole="' + info[a].userrole + '" data-userrole="' + res.content[b].userRole + '" data-id="' + info[a].id + '" data-userid="' + res.content[b]._id + '">' + res.content[b].classifyId + '-' + res.content[b].classifyIdTwo + '-' + info[a].name +"("+res.content[b].todo_doctor+")"+'</option>'; //医生信息
						};
					}
				};
				$(".doctor_select").html(html);
				$(".yaoqing").html(html);
			}
		},
		error: function(err) {
			console.log(err)
		}
	});
};

//
socket.on("room_timeout", (h, s) => {
	layer.open({
		title: '系统提示',
		content: h + '房间已超时!',
		success: function(layero) {
				 layero.find(".layui-layer-btn0").css({
				 	"border-color":"#1abb9c",
				 	"background-color":"#1abb9c"
				 })	
		}
	});
	$.ajax({
		url: "https://xcx.juseyx.cn/service/endroom",
		type: "post",
		dataType: "json",
		data: {
			roomID: h,
			username: $("#name").attr("data-name")
		},
		success: function(res) {
			console.log(res);
			if(res.code == 200) {
				//结束服务删除房间用户信息
				del_temporary(h);
				//退出房间
				socket.emit("leave", {
					roomID: h,
					username: $("#name").attr("data-name"),
					events: "out"
				});
				$('li[rooname="' + h + '"]').remove(); //移除信息展示区
				$('div[roomid="' + h + '"]').remove(); //移除信息展示区
				$(".username").attr("data-id", ""); //清空id
				dont_online(); //判断接待列表是否为空
				self.location.href="#";
			};
		},
		error: function(err) {
			console.log(err)
		}
	});
})